package ch.fhnw.ams.sudoku;

import java.io.File;
import java.io.IOException;
import java.util.Locale;

import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import org.apache.log4j.Logger;

import ch.fhnw.ams.sudoku.gui.SudokuFrame;
import ch.fhnw.ams.sudoku.io.UserProperties;

/**
 * The Main class of Sudoku SideKick. First set up all resources then start an
 * instance of the main application window.
 */
public class Main {
	
	private static final Logger log = Logger.getLogger(Main.class);
	
	
	
    public static void main( String[] args ) throws Exception {
    	log.info(Globals.APP_NAME + " " + Globals.APP_VERSION + " started" + " by " + Globals.USER_NAME);
    	
    	try {
    		createUserHomeDirIfNotExists();
		} catch (IOException e) {
			log.error("could not create user home directory", e);
			return; //exit
		}
    	
    	Locale.setDefault(Locale.US);
    	UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    	
    	//create game and load last saved game
    	final SudokuGame game = new SudokuGame();
    	String gamePath = UserProperties.getInstance().getLastGame();
    	File file = new File(gamePath);
    	if (file.exists() && file.canRead()) {
    		game.load(gamePath);
    	}
    	
    	//start GUI
    	SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				new SudokuFrame(game);
			}
		});
    }
    
    
    private static void createUserHomeDirIfNotExists() throws IOException {
    	File homeDir = new File(Globals.USER_HOME_DIR);
    	
    	if (!homeDir.exists()) {
    		homeDir.mkdir();
    	} 
    	
    	if (!homeDir.exists()) {
    		throw new IOException();
    	}
    }
}
